<template>
  <v-chart :option="option" autoresize />
</template>

<script setup>
import dayjs from "dayjs";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { BarChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import VChart, { THEME_KEY } from "vue-echarts";
import { watch, provide, computed, ref } from "vue";
import { primaryColor, secondaryColor } from "../color";
import { rand } from "@vueuse/core";
import { sum } from "lodash-es";

use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

provide(THEME_KEY, "dark");

const props = defineProps(["timeType", "switch"]);
function currentHour() {
  const current = dayjs().subtract(dayjs().hour(), "hour");
  let dayArr = [];
  for (let i = 0; i < 24; i++) {
    const date = current.add(i, "hour").format("HH:00");
    dayArr.push(date);
  }
  return dayArr;
}

function currentDate() {
  const current = dayjs().subtract(dayjs().date(), "day");
  let dayArr = [];
  for (let i = 1; i <= dayjs().daysInMonth(); i++) {
    const date = current.add(i, "day").format("MM.DD");
    dayArr.push(date);
  }
  console.log(dayArr);
  return dayArr;
}
const yData = ref([]);

function resetYData() {
  yData.value = Array(dayjs().daysInMonth())
    .fill(0)
    .map(() => []);
  for (let i = 0; i < yData.value.length; i++) {
    for (let j = 0; j < 24; j++) {
      if (j >= dayjs().hour() && yData.value.length - 1 >= i) break;
      yData.value[i].push(rand(2, 100));
    }
  }
}
resetYData();

const color = {
  type: "linear",
  x: 0,
  y: 0,
  x2: 0,
  y2: 1,
  colorStops: [
    {
      offset: 0,
      color: secondaryColor,
    },
    {
      offset: 1,
      color: primaryColor,
    },
  ],
};
let preSwitch = "S1";
const option = computed(() => {
  const op = {
    backgroundColor: "rgba(0,0,0,0)",
    xAxis: {
      type: "category",
      data: currentHour(),
      boundaryGap: true,
    },
    yAxis: {
      type: "value",
      splitLine: {
        show: false,
      },
    },
    series: [
      {
        data: [],
        type: "bar",
        itemStyle: {
          color,
        },
      },
    ],
  };
  if (props.switch != preSwitch) {
    resetYData();
    preSwitch = props.switch;
  }
  if (props.timeType === "day") {
    op.xAxis.data = currentDate();
    op.series[0].data = yData.value.map((v) => sum(v));
  } else {
    op.series[0].data = yData.value[dayjs().date() - 1];
  }
  return op;
});
</script>
